package com.qmo.edu.utils;

import android.app.Activity;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.qmo.edu.R;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.qqtheme.framework.picker.DatePicker;
import me.jessyan.autosize.utils.LogUtils;

/**
 * Created by ${安文静} on 2019/6/28.
 *
 * @author cyx
 */
public class FunctionUtils {


    private static boolean sIsCancel = true;

    public static void initDay(Activity context, TextView textView, int year, int month, int day, int type) {

        final DatePicker picker = new DatePicker(context);

        picker.setTopPadding(25);
        picker.setTextSize(18);
        picker.setRangeStart(year, month, day);
        picker.setRangeEnd(Integer.parseInt(initNowData("yyyy")), Integer.parseInt(initNowData("MM")), Integer.parseInt(initNowData("dd")));
        picker.setSelectedItem(Integer.parseInt(initNowData("yyyy")), Integer.parseInt(initNowData("MM")), Integer.parseInt(initNowData("dd")));

        picker.setOnDatePickListener((DatePicker.OnYearMonthDayPickListener) (year1, month1, day1) -> textView.setText(year1 + "-" + month1 + "-" + day1));

        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
        picker.getCancelButton().setText("重置");
        picker.getCancelButton().setOnClickListener(v -> {
            if (type == 1) {
                textView.setText("开始时间");

            } else if (type == 2) {
                textView.setText("结束时间");
            }
            picker.dismiss();
        });
        picker.getCancelButton().setTextSize(18);
        picker.getSubmitButton().setTextSize(18);

    }

    public static String initNowData(String s) {
        SimpleDateFormat formatter = new SimpleDateFormat(s);
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        return str;
    }


    public static void dayNew(Activity context, TextView startData, TextView endData, int year, int month, int day, int type) {
        Calendar startDate = Calendar.getInstance();
        startDate.set(year, month-1, day);//开始的时间
        LogUtils.e("---------" + year + "-----" + month + "------" +day);
        TimePickerView pvTime = new TimePickerBuilder(context, (date, v) -> {
//                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            sIsCancel = false;
            LogUtils.e("----------------6-");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            if(type == 1){
                startData.setText(simpleDateFormat.format(date));
                startData.setTextColor(context.getResources().getColor(R.color.therm_color));
            }else {
                endData.setText(simpleDateFormat.format(date));
                endData.setTextColor(context.getResources().getColor(R.color.therm_color));
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setOutSideCancelable(true)
                .setTitleText("请选择时间")
                .setCancelText("重置")
                .setDate(Calendar.getInstance())//当前选择的时间  主要是这句,  你可以设置 selectDate
                .setRangDate(startDate, Calendar.getInstance())
                .setContentTextSize(24)
                .setSubCalSize(20)
                .setTitleSize(21)
                .build();
        sIsCancel = true;
        pvTime.show();
        pvTime.setOnDismissListener(o -> {
            if (sIsCancel) {
                //这是点的取消
                LogUtils.e("----------------取消-");
                if (type == 1) {
                    startData.setText("开始时间");
                    endData.setText("结束时间");
                    startData.setTextColor(context.getResources().getColor(R.color.gray_900));
                    endData.setTextColor(context.getResources().getColor(R.color.gray_900));
                } else {
                    endData.setText("结束时间");
                    endData.setTextColor(context.getResources().getColor(R.color.gray_900));
                }
            } else {
                LogUtils.e("----------------曲儿-");

            }
        });

    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
        /** 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
         ** 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
         ** 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         * */
        String telRegex = "[1][3456789]\\d{9}";
        // "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) {

            return false;
        } else {

            return mobiles.matches(telRegex);
        }
    }

    public static void fixInputMethodManagerLeak(Context context) {
        if (context == null) {
            return;
        }
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }
        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
        Field f = null;
        Object obj = null;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                }
                obj = f.get(imm);
                if (obj != null && obj instanceof View) {
                    View vGet = (View) obj;
                    if (vGet.getContext() == context) {
                        f.set(imm, null);
                    } else {
                        break;
                    }
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    //邮箱验证
    public static boolean isEmail(String strEmail) {
//        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        String strPattern = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }
    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
            LogUtils.e(  "本软件的版本号。。" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }


}
